package com.srwl.mytx.activity;


import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONObject;
import com.srwl.easeui.widget.MyTitleBar;
import com.srwl.mytx.Constant;
import com.srwl.mytx.Helper;
import com.srwl.mytx.domain.User;
import com.srwl.mytx.R;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.adapter.FollowFansRecordAdapter;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.parse.UserProfileManager;
import com.srwl.mytx.service.UserService;
import com.srwl.mytx.widget.NodataFooter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import me.dkzwm.widget.srl.MaterialSmoothRefreshLayout;
import me.dkzwm.widget.srl.SmoothRefreshLayout;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class FollowFansRecordActivity extends BaseActivity {
    private static final String TAG = "FollowFansRecord";
    private RecyclerView rv_forwardRecord;
    private FollowFansRecordAdapter adapter;
    private ProgressBar progressBar;
    private MyTitleBar titleBar;
    private MaterialSmoothRefreshLayout refreshLayout;
    private List<User> fansList = new ArrayList<>();
    private int page = 1;
    private final int SIZE = 10;
    private boolean hasNextPage = true;
    private boolean isShowFans;
    private String uid;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_follow_fans_record);
        isShowFans = getIntent().getBooleanExtra(Constant.EXTRA_INFO_IS_SHOW_FANS,false);
        uid = getIntent().getStringExtra("uid");
        String loginUserId = UserProfileManager.getInstance().getLoginUserInfo().getuId();
        rv_forwardRecord = findViewById(R.id.rv_forward_record);
        progressBar = findViewById(R.id.progress_bar);
        titleBar = findViewById(R.id.title_bar);
        if (isShowFans) {
            if (uid.equals(loginUserId)) {
                titleBar.setTitle("我的粉丝");
            } else {
                titleBar.setTitle("Ta的粉丝");
            }
        } else {
            if (uid.equals(loginUserId)) {
                titleBar.setTitle("我的关注");
            } else {
                titleBar.setTitle("Ta的关注");
            }
        }
        initRefreshLayout();
        adapter = new FollowFansRecordAdapter(FollowFansRecordActivity.this, fansList);
        rv_forwardRecord.setLayoutManager(new LinearLayoutManager(this, RecyclerView.VERTICAL, false));
        rv_forwardRecord.setAdapter(adapter);
        loadData(true);
    }

    private void initRefreshLayout() {
        refreshLayout = findViewById(R.id.refresh_layout);
        refreshLayout.setEnableOverScroll(false);
        refreshLayout.setDisableRefresh(true);
        //  refreshLayout.setEnableHeaderDrawerStyle(false);
        refreshLayout.setDisableLoadMore(false);
        refreshLayout.setDisableLoadMoreWhenContentNotFull(false);
        refreshLayout.setOnRefreshListener(new SmoothRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefreshing() {

                page = 1;
                loadData(false);
            }

            @Override
            public void onLoadingMore() {

                if (hasNextPage) {
                    loadData(false);
                } else {
                    refreshLayout.refreshComplete();
                    Log.d(TAG, "onRefreshBegin: 没有更多数据了");
                }
            }

        });
    }

    private void loadData(boolean isFirst) {
        if (!Helper.getInstance().isNetworkConnected()){
            if (!isFirst) refreshLayout.refreshComplete();
            showToast_v1(getString(R.string.network_anomalies));
            return;
        }
        Map<String, Object> body = new HashMap<>();
        body.put("page", page);
        body.put("size", SIZE);
        body.put("uId", uid);
        body.put("isShowFans", isShowFans);
        RetrofitManager.getInstance().createRequest(UserService.class)
                .loadFollowFansList(body)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        if (isFirst) {
                            progressBar.setVisibility(View.GONE);
                        } else {
                            refreshLayout.refreshComplete();
                        }
                        CommonResult result = response.body();

                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            adapter.showErrorView();
                            return;
                        }
                        if (result.isError()) {
                            Log.e(TAG, "onResponse: " + result.getMsg());
                            adapter.showErrorView();
                            return;
                        }
                        JSONObject pageInfo = (JSONObject) result.getData();
                        if(pageInfo==null){
                            adapter.showNoDataView();
                        }else {
                            Log.d(TAG, "onResponse: " + pageInfo.toString());
                            pageInfo.getInteger("total");
                            hasNextPage = pageInfo.getBoolean("hasNextPage");
                            if (!hasNextPage) {
                                refreshLayout.postDelayed(() -> refreshLayout.setFooterView(new NodataFooter(FollowFansRecordActivity.this)), 2000);
                            }
                            List<User> fans = pageInfo.getJSONArray("list").toJavaList(User.class);
                            if (fans.size() != 0) {
                                fansList.addAll(fans);
                                adapter.showNormalView();
                                page++;
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        if (isFirst) {
                            progressBar.setVisibility(View.GONE);
                        } else {
                            refreshLayout.refreshComplete();
                        }
                        Log.e(TAG, "onFailure: " + t.getMessage());
                        adapter.showErrorView();
                    }
                });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }
        if (requestCode == FollowFansRecordAdapter.REQUEST_CODE_TO_UserProfileActivity) {
            User user = data.getParcelableExtra(Constant.EXTRA_TARGET_USER);
            String userId = user.getUId();
            for (int i = 0; i < fansList.size(); i++) {
                if (fansList.get(i).getUId().equals(userId)){
                    fansList.set(i,user);
                    adapter.notifyItemChanged(i);
                }

            }
        }
    }
}
